﻿@{
    Layout = "~/Views/Shared/_Dashboard.cshtml";
}
@{
    System.Globalization.CultureInfo fCulture = ViewBag.FromCulture;
    System.Globalization.CultureInfo tCulture = ViewBag.ToCulture;
    string res = Request.QueryString["res"];
    string appID = System.Web.Configuration.WebConfigurationManager.AppSettings["BingAppID"];
    string title = fCulture.LCID == tCulture.LCID ? Html.Global("RES_EDIT") : Html.Global("RES_TRANSLATE");
}
@UIHelper.ImageTitle(title + ":" + Request.QueryString["res"], imgPath: "~/content/images/icon_translate_48.png")
@(Ajax.Dna().CollapsablePanel("toolPanel")
.Header(@<text><div style="line-height: 25px; padding: 5px;">
    @Html.Global("LableEditor_TranslatorTools")</div></text>)
.Width(600)
.Body(@<text>
<table>
    <tr>
        <td>
            @Html.Global("RES_FROM"):@fCulture.DisplayName
        </td>
        <td>
            @Html.Global("RES_TO"):@tCulture.DisplayName
        </td>
    </tr>
    <tr>
        <td style="width: 300px; vertical-align: top; padding: 5px;">
            <div id="orgText">
            </div>
        </td>
        <td style="width: 300px; vertical-align: top;">@Ajax.Dna().TextArea("TranslateResult").Width(270).Height(50).Resizable().GetHtml()
        </td>
    </tr>
    <tr>
        <td align="center">
            @if (!string.IsNullOrEmpty(appID) && (fCulture.LCID != tCulture.LCID))
            {
                @Ajax.Dna().Button("btnBatchTranslate").LocText("LabelEditor_TranslateAll").Click("_batchTranslate();").GetHtml()
                @Ajax.Dna().Button("btnTranslate").LocText("LabelEditor_TranslateByBing").Click("_translate();").GetHtml()
            }
        </td>
        <td align="center">
            @Ajax.Dna().Button("btnSave").LocText("RES_SAVE").Click("_postResult()").GetHtml()
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <div style="text-align: center;" id="progText">
            </div>
        </td>
    </tr>
</table>
</text>)
                .GetHtml()
                )<br />
<div class="ui-state-error" style="width: 580px; padding: 10px; display: none;" id="error_summary">
</div>
<input id="curKey" type="hidden" value="" />
<br />
@{
    Ajax.Dna().Grid<DNA.Mvc.Controllers.Collation>()
        .ClientBind(Url.Action("ResXData", new { res = res, from = fCulture.Name, to = tCulture.Name }))
        .Options(opts =>
        {
            opts.OnRowSelected = "_populateData(ui);";
        })
        .Pagable()
        .Columns(cols =>
        {
            cols.Bound(m => m.Key).Title(fCulture.DisplayName).ClientTemplate(@<text>
    <input type="hidden" value="${Key}" /><p style="width: 200px; white-space: normal;
        margin: 0px;">
        ${Value}</p>
    </text>).Width(300);
            cols.Bound(m => m.Label).Title(tCulture.DisplayName).ClientTemplate(@<text>
    <p id="${Key}" style="width: 200px; white-space: normal; margin: 0px;">
        ${Label}</p>
    </text>).Width(300);
        })
        .Pagable(1, 16)
        .Width(600)
        .Name("ResxGrid")
        .Render();
}
<input type="hidden" id="wordHolder" />
<script type="text/javascript">
    function _populateData(ui) {
        $("#curKey").val(ui.data.Key);
        $("#orgText").html(ui.data.Value);
        $("#TranslateResult").val(ui.data.Label);
    }

    function _postResult() {
        $.post("@(Url.Action("Translate"))",{
        res:"@res",
        lan:"@tCulture.Name",
        key:$("#curKey").val(),
        label:$("#TranslateResult").val()
        },function(){
        $("#ResxGrid_pager").pager("reload"); 
        });

        $("#error_summary").ajaxError(function(event, jqXHR, ajaxSettings, thrownError){
        $(this).text("Ajax error!Your language file could not be write!").show();
        });
    }

    function _batchTranslate() {
      $.ajax({
         url:"@(MvcHtmlString.Create(Url.Action("LoadResXData", new { res = res, lan = tCulture.Name })))",
         type:"json",
         success:function(dict){
            window.$dict=dict;
            window.$index=0;
            window.$end=100;
            $("#progText").text("1/"+dict.length);
            _btCore();
         }
      });
    }
    
    function _batchUpdate(){
        $.post("@(Url.Action("BatchTranslate"))",{
               res:"@res",
               lan:"@tCulture.Name",
               dict:JSON.stringify($dict)
        },function(){ 
            $("#ResxGrid_pager").pager("reload"); 
        });
    }
    
    window._btCallback=function(response){
    $.each(response,function(i,n){
       $dict[$index++].Value=n.TranslatedText;
    });
          $("#progText").text($index+"/"+$dict.length);
          if ($index<$dict.length)
             _btCore();
          else
             _batchUpdate();
       }

    function _btCore() {
    var args=[];
    $end=$index+100;
    if ($end>$dict.length)
      $end=$index+($dict.length-$index);

    for (var i=$index;i<$end;i++)
      args.push(encodeURIComponent($dict[i].Value.replace(/"([^"]*)"/g, "'$1'").replace(/\u000d/g,"").replace(/\u000a/g,"")));
    var options="{\"ContentType\":\"text/html\"}";
    if (args.length==0) return;
    var argStr=JSON.stringify(args);
       var s = document.createElement("script");
      s.src = "http://api.microsofttranslator.com/V2/Ajax.svc/TranslateArray?oncomplete=_btCallback&appId=@(appID)&from=@(fCulture.Parent.Name)&to=@(tCulture.Parent.Name)&texts=" + argStr+"&options"+options ;
       document.getElementsByTagName("head")[0].appendChild(s);
    }

    function _translate() {
        window.mycallback = function (response) {
            $("#TranslateResult").val(response);
        }
        var text = encodeURIComponent($("#orgText").text());
        if ($("#callScript").length) $("#callScript").remove();
        var s = document.createElement("script");
        s.setAttribute("id","callScript");
        s.src = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate?oncomplete=mycallback&appId=@(appID)&from=@(fCulture.Parent.Name)&to=@(tCulture.Parent.Name)&text=" + text;
        $("head").append(s);
    }
</script>
